package com.bosch.in.rtp1.ept.util.job;

import javax.servlet.ServletException;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;
/**
 * class is used to setup running job which is periodically check 
 * if data is changed by daily store procedure, then it will clear existing cache data
 * so that we are able to get new changes.
 * @author TPR1HC
 *
 */
public class QuartzPlugin implements PlugIn {
	
	// group name
	public static final String GROUP = "group1";
	// job name
	private static final String JOB = "job1";
	// trigger name
	public static final String TRIGGER = "trigger1";
	
	// job will be run every 5 minutes
	public static final String CRON_SCHEDULE_MINUTE = "0 0/15 ";
	//  every hour. This is just start guest because we don't know when data is updated, 
	//	it will be rescheduled according to time we get new updated data.
	public static final String CRON_SCHEDULE_HOUR = "*";
	// job repeat every day. 
	public static final String CRON_SCHEDULE_DAY = " * * ?";
	
	private static final Logger LOGGER = Logger.getLogger(QuartzPlugin.class);
	
	@Override
	public void destroy() {
		// null
	}

	
	
	@Override
	public void init(ActionServlet servlet, ModuleConfig config)
			throws ServletException {

		JobDetail job = JobBuilder.newJob(SchedulerJob.class)
				.withIdentity(JOB, GROUP).build();

		TriggerKey triggerKey = new TriggerKey(TRIGGER, GROUP);
		
		try {

			Trigger trigger = TriggerBuilder
					.newTrigger()
					.withIdentity(triggerKey)
					.withSchedule(CronScheduleBuilder.cronSchedule(
							CRON_SCHEDULE_MINUTE + CRON_SCHEDULE_HOUR + CRON_SCHEDULE_DAY))
					.build();

			Scheduler scheduler = new StdSchedulerFactory().getScheduler();
			scheduler.start();
			scheduler.scheduleJob(job, trigger);

		} catch (SchedulerException e) {
			e.printStackTrace();
			LOGGER.error(e.getMessage());
		}

	}

}
